import { useState, useRef } from "react";

// 函数组件：注意大驼峰命名规则
function TodoList() {

    const [list, setList] = useState([]);
    const inputRef = useRef();
    let id = 1;

    // 点击提交按钮
    function handleSubmit() {
        const value = inputRef.current.value;
        if (value) {
            list.push({value,checked: false});
            // 更新状态，渲染组件
            setList([...list]);

            inputRef.current.value = "";
        }
    }

    function deleteByIndex(i) {
        list.splice(i,1);
        setList([...list]);
    }

    function checkChange(item) {
        // console.log("我变了")
        item.checked = !item.checked;
        // list.splice(i,1);
        setList([...list]);
        console.log(list.filter(v => v.checked).length);
    }

    return (
        <div>
            <h1>todo-list</h1>
            <div>
                <input type="text" ref={inputRef} />
                <button onClick={handleSubmit}>提交</button>
            </div>
            {list.map((v,i) => <ListItem key={id ++} 
            item={v} 
            i={i} 
            deleteByIndex={deleteByIndex}
            checkChange={checkChange}/>)}
        </div>
    )
}

function ListItem(props) {
    return (
        <li>
            <input type="checkbox" onChange={() => props.checkChange(props.item)}></input>
            <span>{props.item.value}</span>
            <button onClick={() => props.deleteByIndex(props.i)}  
            checked={props.item.checked}>删除</button>
        </li>
    )
}

// 记得export default
export default TodoList;